package ckw.database.model;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Transient;

import org.hibernate.annotations.Type;

import core.util.Converter;

@Entity(name = "ckw.Election")
public class Election extends core.database.Election<ElectionVoter> {
	private static final long serialVersionUID = 4512566609243769237L;
	
	@Column(name = "results")
	@Type(type = "text")
	private String results;
	@Column(name = "isSend", nullable = false)
	private Boolean isSend = false;
	@OneToMany
	@JoinColumn(name = "election")
	private Set<ElectionNode> nodes = new HashSet<ElectionNode>();
//	@OneToMany
//	@JoinColumn(name = "election")
//	private Set<ElectionVoter> voters = new HashSet<ElectionVoter>();
	@Column(name = "changesXML")
	@Type(type = "text")
	private String changesXML;
	@Transient
	private ElectionChanges changes = null;

	public String getResults() {
		return results;
	}

	public void setResults(String results) {
		this.results = results;
	}

	public Boolean getIsSend() {
		return isSend;
	}

	public void setIsSend(Boolean isSend) {
		this.isSend = isSend;
	}

	public Set<ElectionNode> getNodes() {
		return nodes;
	}

	public void setNodes(Set<ElectionNode> nodes) {
		this.nodes = nodes;
	}

//	public Set<ElectionVoter> getVoters() {
//		return voters;
//	}
//
//	public void setVoters(Set<ElectionVoter> voters) {
//		this.voters = voters;
//	}

	public String getChangesXML() {
		return changesXML;
	}

	public void setChangesXML(String changesXML) {
		this.changesXML = changesXML;
	}

	@PrePersist
	@PreUpdate
	private void convertChanges() {
		if (changes != null)
			setChangesXML(Converter.objectToXML(changes));
	}

	public ElectionChanges getChanges() {
		return changes;
	}

	public void setChanges(ElectionChanges changes) {
		this.changes = changes;
	}
	
	@PostConstruct
	@PostLoad
	private void convertChangesXML() {
		if (changesXML != null) 
			setChanges((ElectionChanges)Converter.XMLToObject(changesXML));
	}
}
